<template>
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="70%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="page-note-form"
    >
      <el-form-item label="页面名称" prop="pageName">
        <el-input v-model="formData.pageName" placeholder="请输入页面名称" />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 400px; overflow-y: hidden;"
            v-model="formData.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, shallowRef, onBeforeUnmount } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import { pageNoteModel, type PageNote } from './pageNoteModel'

const props = defineProps<{
  visible: boolean
  editData?: PageNote
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const dialogTitle = computed(() => props.editData ? '编辑页面笔记' : '新增页面笔记')

const formRef = ref<FormInstance>()
const loading = ref(false)

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 模式
const mode = ref('default')

// 工具栏配置
const toolbarConfig = {
  excludeKeys: [
    'uploadVideo',
    'insertTable',
    'codeBlock',
    'todo'
  ]
}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...'
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 编辑器回调函数
const handleCreated = (editor: any) => {
  editorRef.value = editor
}

const formData = reactive<PageNote>({
  pageName: '',
  title: '',
  content: ''
})

const rules: FormRules = {
  pageName: [
    { required: true, message: '请输入页面名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (props.editData) {
    Object.assign(formData, props.editData)
  } else {
    formData.pageName = ''
    formData.title = ''
    formData.content = ''
  }
}

// 监听 visible 变化
watch(() => props.visible, (val) => {
  if (val) {
    initFormData()
  }
})

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (props.editData) {
          await pageNoteModel.updatePageNote(formData)
        } else {
          await pageNoteModel.addPageNote(formData)
        }
        emit('success')
        handleClose()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.page-note-form {
  padding: 20px;
}

.editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: #fff;
}

:deep(.w-e-text-container) {
  min-height: 400px !important;
}

:deep(.w-e-toolbar) {
  border-top: none !important;
  border-left: none !important;
  border-right: none !important;
}

:deep(.w-e-text) {
  padding: 0 10px !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style> 
